//
//  LoginViewController.m
//  GainInvest
//
//  Created by 王玉龙 on 17/2/8.
//  Copyright © 2017年 longlong. All rights reserved.
//

#import "LoginViewController.h"


#import "ValidateClass.h"
#import "LoginHttpManager.h"
#import "RegisterViewController.h"
#import <UMSocialCore/UMSocialCore.h>
#import "AppDelegate.h"

@interface LoginViewController ()

{
    
    __weak IBOutlet UITextField *_phoneTf;
    __weak IBOutlet UITextField *_passwordTf;
    
}

@property (nonatomic ,strong) LoginHttpManager *httpManager;

@end

@implementation LoginViewController

- (void)dealloc
{
    _httpManager = nil;
}

- (LoginHttpManager *)httpManager
{
    if (_httpManager == nil)
    {
        _httpManager = [[LoginHttpManager alloc]init];
    }
    
    return _httpManager;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self customNavBar];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)customNavBar
{
    self.navigationItem.title = @"登录";
    
    LeftBackItem *leftBarItem = [[LeftBackItem alloc] initWithTarget:self Selector:@selector(leftNavBarButtonClick)];
    self.navigationItem.leftBarButtonItem=leftBarItem;

}

- (void)leftNavBarButtonClick
{
    [self textFiledResignFirstResponder];

    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}


- (IBAction)passwordSecureButtonClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (sender.selected)
    {
        _passwordTf.secureTextEntry = NO;
    }
    else
    {
        _passwordTf.secureTextEntry = YES;
    }
}

- (IBAction)loginButtonClick:(UIButton *)sender
{
    [self textFiledResignFirstResponder];

    if ([self isLeaglePasswordLoginMethod] == NO)
    {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    hud.label.text = @"登录...";
    
    [self.httpManager loginWithAccount:_phoneTf.text Password:_passwordTf.text CompletionBlock:^(AccountInfo *user, NSError *error)
     {
         [hud hideAnimated:YES];
         
         if (error)
         {
             [ErrorTipView errorTip:error.domain SuperView:self.view];
         }
         else
         {
             [user storeAccountInfo];//存储数据
             
             [self.navigationController dismissViewControllerAnimated:YES completion:nil];
         }        
     }];

}

- (IBAction)forgetButtonClick:(UIButton *)sender
{
    [self textFiledResignFirstResponder];

    // 忘记密码
    RegisterViewController *registerVC = [[RegisterViewController alloc]initWithIsRegister:NO];
    [self.navigationController pushViewController:registerVC animated:YES];
}

- (IBAction)registerButtonClick:(UIButton *)sender
{
    [self textFiledResignFirstResponder];

    
    RegisterViewController *registerVC = [[RegisterViewController alloc]initWithIsRegister:YES];
    [self.navigationController pushViewController:registerVC animated:YES];
}

- (IBAction)weChatLoginButtonClick:(UIButton *)sender
{
    [self thirdPartyLoginWithPlayform:UMSocialPlatformType_WechatSession Type:@"1"];
}

- (IBAction)qqLoginButtonClick:(UIButton *)sender
{
    [self thirdPartyLoginWithPlayform:UMSocialPlatformType_QQ Type:@"2"];
}

- (BOOL)isLeaglePasswordLoginMethod
{
    if ([ValidateClass isMobile:_phoneTf.text] == NO)
    {
        if (_phoneTf.text.length == 0)
        {
            [ErrorTipView errorTip:@"请输入手机号" SuperView:self.view];
        }
        else
        {
            [ErrorTipView errorTip:@"手机号格式有误" SuperView:self.view];
        }
        
        return NO;
    }
    
    if (_passwordTf.text.length < 1)
    {
        [ErrorTipView errorTip:@"密码不得为空" SuperView:self.view];
        
        return NO;
    }
    
    
    return YES;
}

- (void)thirdPartyLoginWithPlayform:(UMSocialPlatformType)platformType Type:(NSString *)type
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType currentViewController:self completion:^(id result, NSError *error)
     {
         UMSocialUserInfoResponse *resp = result;
         
         NSLog(@"error ====== %@",error);
         
         // 第三方登录数据(为空表示平台未提供)
         // 授权数据
         NSLog(@" result: %@", resp);
         NSLog(@" uid: %@", resp.uid);
         NSLog(@" openid: %@", resp.openid);
         NSLog(@" accessToken: %@", resp.accessToken);
         NSLog(@" refreshToken: %@", resp.refreshToken);
         NSLog(@" expiration: %@", resp.expiration);
         
         // 用户数据
         NSLog(@" name: %@", resp.name);
         NSLog(@" iconurl: %@", resp.iconurl);
         NSLog(@" gender: %@", resp.gender);
         
         // 第三方平台SDK原始数据
         NSLog(@" originalResponse: %@", resp.originalResponse);
         
         if (resp.uid && resp.name &&resp.iconurl )
         {
             
             ThirdLoginModel *model = [[ThirdLoginModel alloc]init];
             model.nickname = resp.name;
             model.iconurl = resp.iconurl;
             model.uid = resp.uid;
             model.openid = resp.openid;
             model.accessToken = resp.accessToken;
             model.refreshToken = resp.refreshToken;
             model.expiration = resp.expiration;
             model.platfrom = type;
             
             
             
             
             [self thirdPartyLoginWithModel:model];
             
         }
     }];

}

- (void)thirdPartyLoginWithModel:(ThirdLoginModel *)thirdModel
{
    NSDictionary *parameterDict = @{@"openid":thirdModel.uid,@"type":thirdModel.platfrom,@"nickname":thirdModel.nickname,@"head":thirdModel.iconurl,@"token":@"4zpSrxbyMdSRM2fj",@"froms":@"iOS"};

    
    [self.httpManager thirdPartyLoginWithParameterDict:parameterDict CompletionBlock:^(AccountInfo *user, NSError *error)
    {
        NSLog(@"code == %ld",(long)error.code);
        
        NSLog(@"errString == %@",error.domain);
        if (error)
        {
            if (error.code == 1)
            {
                AccountInfo *account = [AccountInfo modelObjectWithThirdModel:thirdModel];
                [account storeAccountInfo];
                [self leftNavBarButtonClick];
                NSLog(@"存储数据成功");

            }

        }
        else
        {
            
            
            if ([user storeAccountInfo])
            {
                //登录成功后IM登录
                [AuthorizationManager getIM_Authorization];
                //存储数据
                //登录成功，进入主界面
                [self leftNavBarButtonClick];
                
                NSLog(@"存储数据成功");
                
            }
            else
            {
                NSLog(@"存储数据失败");
            }

        }

    }];

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self textFiledResignFirstResponder];
}

- (void)textFiledResignFirstResponder
{
    [_passwordTf endEditing:YES];
    [_phoneTf endEditing:YES];

}

@end
